package com.shy.config.util;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.time.Duration;

@Configuration
public class RedisCacheConfig {
    private static final Long CACHE_TIME = 60 * 60 * 24L;

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //创建缓存管理器
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration
                // 使用默认缓存配置
                .defaultCacheConfig()
                // 设置缓存项的存活时间为CACHE_TIME秒
                .entryTtl(Duration.ofSeconds(CACHE_TIME))
                // 禁止缓存空值
                .disableCachingNullValues()
                // 使用RedisSerializationContext的SerializationPair来序列化键
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))
                // 使用RedisSerializationContext的SerializationPair来序列化值
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));

        return RedisCacheManager
                .builder(redisConnectionFactory)
                .cacheDefaults(redisCacheConfiguration)
                .build();
    }
}
